<template>
  <view class="create-container">
    <!-- 头部标题 -->
    <view class="header">
      <text class="title">新建展览</text>
    </view>

    <!-- 展览表单组件 -->
    <ExhibitionForm 
      ref="exhibitionFormRef"
      :initial-data="initialFormData"
      :hide-media="true"
    />
    <view class="bottom-action">
      <button class="save-large-btn" @click="saveExhibition">保存</button>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { createRecord, getRecordList, uploadSingleImage, updateRecord } from '@/services/api/backendApi'
import ExhibitionForm from '@/components/ExhibitionForm.vue'

// 表单组件引用
const exhibitionFormRef = ref(null)

// 初始表单数据（新建时为空）
const initialFormData = ref({})

// 页面加载时的处理
onLoad((query) => {
  console.log('🧭 [新建展览] onLoad 参数:', query)
  // 新建展览时，可以接收一些预设数据（比如从创作中心传来的）
  if (query && query.fromCreation === 'true') {
    initialFormData.value = { fromCreation: true }
  }
  // import模式：保存成功后跳到“从现有展览导入”页
  if (query && query.mode === 'import') {
    initialFormData.value = { ...initialFormData.value, mode: 'import' }
  }
})

// 保存展览
async function saveExhibition() {
  // 获取表单组件的数据和验证结果
  const formData = exhibitionFormRef.value?.getFormData()
  const isValid = exhibitionFormRef.value?.validateForm()
  
  if (!isValid || !formData) {
    return
  }
  // 去重校验：同名展览不允许重复创建（前端兜底，后端仍需强校验）
  try {
    const titleToCheck = (formData.title || '').trim().toLowerCase()
    if (titleToCheck) {
      console.log('🔎 [新建展览] 前置去重校验，title =', titleToCheck)
      const listRes = await getRecordList(1, 100)
      const listData = listRes?.data || listRes
      const existing = (listData?.records || []).some(r => (r.title || '').trim().toLowerCase() === titleToCheck)
      if (existing) {
        uni.showToast({ title: '该展览名称已存在', icon: 'none' })
        return
      }
    }
  } catch (e) {
    console.warn('⚠️ [新建展览] 去重校验失败（忽略并继续后端校验）:', e)
  }
  
  // 准备保存的数据
  const exhibitionData = {
    ...formData,
    id: Date.now(),
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
    // 为了兼容艺术足迹页面的显示，添加location字段
    location: formData.museum,
    // 标记是否使用了预设图片（从创作中心创建的展览可能使用预设图片）
    hasPresetImages: formData.fromCreation || false
  }
  
  // 保存到后端数据库
  console.log('=== 开始创建新展览 ===');
  console.log('展览数据:', exhibitionData);
  
  try {
    // 防抖：按钮禁用，避免多次点击
    if (saveExhibition._busy) return
    saveExhibition._busy = true
    // 调用API创建展览记录
    const recordData = {
      title: exhibitionData.title,
      galleryName: exhibitionData.museum,
      exhibitionDate: exhibitionData.date,
      country: exhibitionData.country || '',
      city: exhibitionData.city || '',
      artist: exhibitionData.artist || '',
      styleTags: exhibitionData.styleTags || '',
      notes: exhibitionData.notes || '',
      aiSummary: exhibitionData.aiSummary || ''
    };
    
    console.log('📤 [新建展览] 调用创建展览记录API:', recordData);
    const createResult = await createRecord(recordData);
    console.log('✅ [新建展览] 展览记录创建成功:', createResult);
    
    // 更新本地数据，使用服务器返回的recordId
    exhibitionData.id = createResult.recordId;
    exhibitionData.recordId = createResult.recordId;

    // 新建页不再上传任何展览图片；创建成功后由“选择图片”流程绑定图片
    
    // 通过事件总线通知艺术足迹页面更新数据
    console.log('📣 [新建展览] 广播事件 exhibitionSaved:', exhibitionData)
    uni.$emit('exhibitionSaved', exhibitionData);
    
    uni.showToast({ title: '保存成功', icon: 'success' });
    // 如为导入模式，直接跳到从已有展览导入
    if (initialFormData.value.mode === 'import') {
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/image-import/exhibition-image-selector' })
      }, 600)
    }
    
  } catch (error) {
    console.error('❌ 创建展览失败:', error);
    
    // 如果API未实现，使用模拟数据
    if (error.message && error.message.includes('404')) {
      console.log('🔄 API未实现，使用模拟数据');
      exhibitionData.id = exhibitionData.id || Date.now();
      exhibitionData.recordId = exhibitionData.id.toString();
      
      // 通过事件总线通知艺术足迹页面更新数据
      console.log('📣 [新建展览] 广播事件 exhibitionSaved (模拟):', exhibitionData)
      uni.$emit('exhibitionSaved', exhibitionData);
      
      uni.showToast({ title: '保存成功（模拟）', icon: 'success' });
    } else {
      uni.showToast({ title: '保存失败，请重试', icon: 'error' });
      return
    }
  } finally {
    saveExhibition._busy = false
  }
  
  // 如果是从创作中心创建的，返回创作中心并传递展览数据
  if (formData.fromCreation) {
    setTimeout(() => {
      // 构造展览记录数据，兼容API格式
      const recordData = {
        recordId: exhibitionData.id.toString(),
        title: exhibitionData.title,
        galleryName: exhibitionData.museum,
        exhibitionDate: exhibitionData.date,
        country: exhibitionData.country,
        city: exhibitionData.city,
        artist: exhibitionData.artist,
        styleTags: exhibitionData.styleTags,
        notes: exhibitionData.notes,
        aiSummary: exhibitionData.aiSummary
      }
      
      // 通过事件总线通知创作中心
      uni.$emit('exhibitionCreated', recordData)
      
      // 返回创作中心
      uni.navigateBack({
        delta: 2 // 返回两层，跳过历史足迹页面
      })
    }, 1500)
  } else {
    // 普通保存或import模式
    setTimeout(() => {
      if (initialFormData.value.mode === 'import') {
        console.log('🔀 [新建展览] import模式，跳到已有展览选择页')
        uni.redirectTo({ url: '/pages/image-import/exhibition-image-selector' })
      } else {
        uni.navigateBack()
      }
    }, 1000)
  }
}
</script>

<style lang="scss" scoped>
.create-container {
  min-height: 100vh;
  background: #1a1a1a;
  padding: 40rpx;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 48rpx;
  
  .title {
    font-size: 26px;
    font-weight: 700;
    color: #ffffff;
    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  }
  
  .save-btn {
    background: linear-gradient(135deg, #ff0050, #ff4081);
    color: #ffffff;
    border: none;
    border-radius: 40rpx;
    padding: 16rpx 40rpx;
    font-size: 14px;
    font-weight: 600;
    left: 100px;
  }
}

.bottom-action {
  margin-top: 32rpx;
  padding: 0 4vw 5vh 4vw; /* 与页面左右留白、底部安全区保持一致 */
}

.save-large-btn {
  width: 100%;
  height: 44px;
  background: #0FFDCD;
  color: #0c0c0c;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 700;
}
</style>
